package com.lk.mi.controller;

import com.lk.mi.entity.item;
import com.lk.mi.service.itemService;
import com.lk.mi.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private itemService itemService;

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 查询所有商品
     * @param model
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<item> list = itemService.findAll();
        model.addAttribute("list",list);
        return "/pages/mall.jsp";
    }

    /**
     * 查询商品详细信息
     * @param iid
     * @param model
     * @return
     */
    @RequestMapping("/getDetail")
    public String getDetail(Integer iid,Model model){
        item item=itemService.findById(iid);
        model.addAttribute("item",item);
        return "/pages/detail.jsp";
    }

    /**
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findById")
    public String findById(Integer id,Model model){
        item item = itemService.findById(id);
        model.addAttribute("item",item);
        return null;
    }

    /**
     * 修改商品信息
     * @param item
     * @return
     */
    public String update(item item){
        Integer row = itemService.update(item);
        //修改成功
        if (row==1){

        }
        //修改失败
        return null;
    }

    /**
     * 删除商品
     * @param
     * @return
     */
    @RequestMapping("/delete")
    public String delete(Integer iid){
        itemService.delete(iid);
        return "/item/findAll";
    }

    /**
     * 添加商品
     * @param item
     * @return
     */
    @RequestMapping("/add")
    public String add(MultipartFile file,item item){

            try {
                //原始文件名
                String originalFilename = file.getOriginalFilename();
                //截取原始文件名的后缀
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                //构造新文件名
                String objectName = UUID.randomUUID().toString();
                objectName=objectName+extension;
                //文件请求路径
                String Path = aliOssUtil.upload(file.getBytes(), objectName);
                item.setImage(Path);
            } catch (IOException e) {
                e.printStackTrace();
            }

                itemService.add(item);

        return "/item/findAll";

    }

}
